package com.cobra.activiti.controller;

import com.alibaba.fastjson.JSON;
import com.cobra.activiti.pojo.dto.ConditionDTO;
import com.cobra.activiti.pojo.param.SingleBusinessKeyParam;
import com.cobra.activiti.pojo.param.SingleIdParam;
import com.cobra.activiti.pojo.param.TaskCompleteParam;
import com.cobra.activiti.pojo.param.TaskOwnerParam;
import com.cobra.activiti.pojo.vo.HistoryTaskVO;
import com.cobra.activiti.pojo.vo.PageVO;
import com.cobra.activiti.pojo.vo.TaskVO;
import com.cobra.activiti.response.ResultVOUtil;
import com.cobra.activiti.response.ReturnValueLoader;
import com.cobra.activiti.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Attachment;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yaobin
 * @date 2020/4/20 0020 17:27
 * @Description 流程实例
 */
@RestController
@Slf4j
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    /**
     * 查看自己的待办事件
     *
     * @param requestParam
     * @return
     */
    @PostMapping("/todoListByOwner")
    public ReturnValueLoader<PageVO<TaskVO>> todoListByOwner(//@ApiParam(name = "receiveSwitchUpdateRequestVO", value = "json格式", required = true)
                                                             @Valid @RequestBody TaskOwnerParam requestParam) {

        PageVO<TaskVO> result = new PageVO<>();
        Integer current = requestParam.getCurrent();
        Integer queryPage = current - 1;
        Integer size = requestParam.getSize();
        String owner = requestParam.getOwner();

        Long count = taskService.createTaskQuery().taskOwner(owner).count();
        Integer intCount = count.intValue();
        List<Task> taskList = taskService.createTaskQuery().taskOwner(owner).orderByTaskCreateTime().desc().listPage(queryPage, size);
        List<TaskVO> taskVOList = taskList.stream().map(task -> {
            TaskVO taskVO = new TaskVO();
            taskVO.setTaskId(task.getId());
            taskVO.setTaskOwner(task.getOwner());
            taskVO.setProcessInstanceId(task.getProcessInstanceId());
            taskVO.setCrateTime(task.getCreateTime());
            return taskVO;
        }).collect(Collectors.toList());

        result.setRecords(taskVOList);
        result.setTotal(intCount);
        result.setSize(size);
        result.setCurrent(current);

        return ResultVOUtil.success(result);
    }

    /**
     * 委办人完成自己的任务
     *
     * @param requestParam
     * @return
     */
    @PostMapping("/completeByOwner")
    public ReturnValueLoader completeByOwner(//@ApiParam(name = "receiveSwitchUpdateRequestVO", value = "json格式", required = true)
                                             @Valid @RequestBody TaskCompleteParam requestParam) {

        String taskId = requestParam.getTaskId();
        String processInstanceId = requestParam.getProcessInstanceId();
        String handler = requestParam.getHandler();
        String assignee = requestParam.getAssignee();
        String comment = requestParam.getComment();
        String condition = requestParam.getCondition();

        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if (task == null) {
            return ResultVOUtil.error("代办任务不存在或已处理，请重新刷新列表确认！");
        }

        if (!handler.equals(task.getOwner())) {
            return ResultVOUtil.error("不是指定代办人，无权处理！");
        }
        //设置流转条件
        Map<String, Object> variables = new HashMap<>(1);

        if (condition != null) {
            ConditionDTO conditionDTO = JSON.parseObject(condition, ConditionDTO.class);
            variables.put(conditionDTO.getKey(), conditionDTO.getValue());
        }

        taskService.addComment(task.getId(), null, comment);
        taskService.complete(task.getId(), variables);

        Task nextTask = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();

        //如果流程还没完成，设置下一个任务的owner
        if (nextTask != null) {
            taskService.setOwner(nextTask.getId(), assignee);
        }

        return ResultVOUtil.success("完成待办任务！");
    }

    /**
     * 根据businessKey获取操作信息，查询某流程的所有历史任务实例
     *
     * @param requestParam
     * @return
     */
    @PostMapping("/processInstanceTaskHistoryByBusinessKey")
    public ReturnValueLoader getTaskHistoryByBusinessKey(//@ApiParam(name = "receiveSwitchUpdateRequestVO", value = "json格式", required = true)
                                                         @Valid @RequestBody SingleBusinessKeyParam requestParam) {

        String businessKey = requestParam.getBusinessKey();

        List<HistoricTaskInstance> historicTaskList = historyService.createHistoricTaskInstanceQuery().
                processInstanceBusinessKey(businessKey).orderByTaskCreateTime().asc().list();

        return getReturnValueLoader(historicTaskList);
    }

    /**
     * 根据processInstanceId获取操作信息，查询某流程的所有历史任务实例
     *
     * @param requestParam
     * @return
     */
    @PostMapping("/processInstanceTaskHistoryById")
    public ReturnValueLoader getTaskHistoryById(//@ApiParam(name = "receiveSwitchUpdateRequestVO", value = "json格式", required = true)
                                                @Valid @RequestBody SingleIdParam requestParam) {

        Integer id = requestParam.getId();

        List<HistoricTaskInstance> historicTaskList = historyService.createHistoricTaskInstanceQuery().
                processInstanceId(id.toString()).orderByTaskCreateTime().asc().list();

        return getReturnValueLoader(historicTaskList);
    }

    /**
     * 转换返回分页信息HistoryTaskVO
     *
     * @param historicTaskList
     * @return
     */
    private ReturnValueLoader getReturnValueLoader(List<HistoricTaskInstance> historicTaskList) {
        List<HistoryTaskVO> historyTaskVOList = historicTaskList.stream().map(historicTaskInstance -> {
            HistoryTaskVO historyTaskVO = new HistoryTaskVO();
            historyTaskVO.setName(historicTaskInstance.getName());
            List<Comment> taskComments = taskService.getTaskComments(historicTaskInstance.getId());

            if (taskComments != null && taskComments.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (Comment taskComment : taskComments) {
                    sb.append(taskComment.getFullMessage());
                }
                historyTaskVO.setComment(sb.toString());
            }

            List<Attachment> taskAttachments = taskService.getTaskAttachments(historicTaskInstance.getId());
            if (taskAttachments != null && taskAttachments.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (Attachment taskAttachment : taskAttachments) {
                    sb.append(taskAttachment.getUrl());
                }
                historyTaskVO.setAttachment(sb.toString());
            }
            historyTaskVO.setStartTime(historicTaskInstance.getStartTime());
            historyTaskVO.setEndTime(historicTaskInstance.getEndTime());
            historyTaskVO.setDuration(DateUtil.getTimeDiffStr(historicTaskInstance.getDurationInMillis()));
            return historyTaskVO;
        }).collect(Collectors.toList());

        return ResultVOUtil.success(historyTaskVOList);
    }

}
